package com.yuexun.dhdoctor.widget;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.config.ScreenUtil;

public class SearchDialog extends Dialog implements View.OnClickListener{
    private OnSearchListener searchListener;
    private EditText searchE;
    private String searchHint;

    public SearchDialog(Context context) {
        this(context, context.getString(R.string.search_hint_default));
    }

    public SearchDialog(Context context, String searchHint) {
        super(context, R.style.MyDialog);
        this.searchHint = searchHint;

        setContentView(R.layout.dialog_search);

        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.gravity = Gravity.TOP;
        params.width = ScreenUtil.getScreenWidth(context);
        getWindow().setAttributes(params);

        this.setCanceledOnTouchOutside(true);

        initView();
    }

    private void initView() {
        findViewById(R.id.back).setOnClickListener(this);
        searchE = (EditText)findViewById(R.id.et_search);
        searchE.setHint(searchHint);
        findViewById(R.id.btn_right_search).setOnClickListener(this);
    }

    private void search() {
        String stringSearch = searchE.getText().toString().trim();

        this.dismiss();
        searchE.setText("");

        if(null != searchListener) {
            searchListener.onSearch(stringSearch);
        }
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.btn_right_search:
                search();
                break;
            case R.id.back:
                this.dismiss();
                break;
        }
    }

    public void setSearchText(String text) {
        searchE.setText(text);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            this.dismiss();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void setSearchListener(OnSearchListener searchListener) {
        this.searchListener = searchListener;
    }

    public interface OnSearchListener {
        void onSearch(String stringSearch);
    }
}
